<?php

namespace Modules\Admin\Http\Controllers\ActivationCodes;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\ActivationCodeLogs;
use Modules\Common\Models\ActivationCodes;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;


class Retrieve
{

    /**
     * @Route(path=/api/admin/activation-code)
     */
    public function retrieve()
    {
        $query = ActivationCodes::with(['adminUser','subscriptionTypes']);

        //激活码
        if (request('code')) {
            $query->where('code', 'like', '%' . request('code') . '%');
        }

        //订阅类型
        if (request('subscription_type_id')) {
            $query->where('subscription_type_id', '=', request('subscription_type_id'));
        }

        //状态
        if (request('status')) {
            $query->where('stauts', '=', request('stauts'));
        }

        $query->orderByRaw('id desc , created_at desc');

        $sidDefault = auth('api')->user()->sid;
        $eidDefault = auth('api')->user()->eid; 
        $data = $query->where('sid',$sidDefault)->where('eid',$eidDefault)->paginate(request('per_page', 15));

        return Api::success($data);
    }
    
    
     /**
     * @Route(path=/api/admin/activation-code-usage)
     */
    public function retrievetwo()
    {
        $query = ActivationCodeUsage::with(['user','subscriptionTypes']);

        //激活码
        if (request('code')) {
            $query->where('code', 'like', '%' . request('code') . '%');
        }

        //订阅类型
        if (request('subscription_type_id')) {
            $query->where('subscription_type_id', '=', request('subscription_type_id'));
        }
        
        $nickname = request('nickname');
        if ($nickname) {
            // 获取匹配昵称的用户 ID 列表
            $userIds = DB::connection('platform')->table('customer')
                ->where('nickname', 'like', '%' . $nickname . '%')
                ->pluck('id')
                ->all();
        
            // 确保获取到了用户 ID
            if (count($userIds) > 0) {
                $query->whereIn('user_id', $userIds);
            } else {
                // 如果没有匹配的用户，返回空结果
                $query->whereNull('user_id');
            }
        }
        
        // 时间范围查询
        $startAt = request('start_at');
        if ($startAt) {
            $query->where('created_at', '>', $startAt);
        }
    
        $endAt = request('end_at');
        if ($endAt) {
            $query->where('created_at', '<', $endAt);
        }

        $query->orderByRaw('id desc , created_at desc');

        $sidDefault = auth('api')->user()->sid;
        $eidDefault = auth('api')->user()->eid;
        $data = $query->where('eid',$eidDefault)->paginate(request('per_page', 15));

        return Api::success($data);
    }
}